package com.hckjsec.cloud.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hckjsec.cloud.domain.*;
import com.hckjsec.cloud.domain.view.BasicView;
import com.hckjsec.cloud.domain.view.MessageView;
import com.hckjsec.cloud.enums.BasicParamEnum;
import com.hckjsec.cloud.message.SendWxMessage;
import com.hckjsec.cloud.message.TempToken;
import com.hckjsec.cloud.message.TemplateData;
import com.hckjsec.common.config.FileInfoView;
import com.hckjsec.common.enums.SysFileTypeEnum;
import com.hckjsec.common.init.YwInitData;
import com.hckjsec.common.utils.DateUtils;
import com.hckjsec.common.utils.StringUtils;
import com.hckjsec.common.utils.TxSmsUtil;
import com.hckjsec.common.utils.file.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import com.hckjsec.common.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WxSendTplMessageService {
    @Autowired
    private YwInitData ywInitData;
    @Autowired
    private IAppletsBusinessTemplateLogService appletsBusinessTemplateLogService;
    @Autowired
    private IAppletsApplicantUserService appletsApplicantUserService;
    @Async
    public void sendMessageSetMaterial(String type,Long configId,AppletsBusiness appletsBusiness,String roomid) {
        try {
            AppletsBusinessTemplateLog appletsBusinessTemplateLog = new AppletsBusinessTemplateLog();
            BasicView basicView= JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(configId)),BasicView.class);
            AppletsConfig appletsConfig=JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigViewMap().get(configId)),AppletsConfig.class);
            TempToken tempToken = new TempToken(appletsConfig.getAppid(),appletsConfig.getAppsecret());
            tempToken.setOpenid(appletsBusiness.getOpenid());
            if("bid".equals(type)){
                tempToken.setTemplate_id(basicView.getTemplate().getBidTemplate());
                tempToken.setPage("/pages/index/index?toPage=");
                exeBidData(tempToken,appletsBusiness);
                appletsBusinessTemplateLog.setTemplatetype("审核结果通知");
            }else if("materials".equals(type)){
                tempToken.setTemplate_id(basicView.getTemplate().getMaterialsTemplate());
                tempToken.setPage("/pages/index/index?toPage=");
                exeMaterialsData(tempToken,appletsBusiness);
                appletsBusinessTemplateLog.setTemplatetype("补充材料通知");
            }else if("video".equals(type)){
                tempToken.setTemplate_id(basicView.getTemplate().getVideoTemplate());
                tempToken.setPage("/pages/index/index?roomID="+roomid);
                exeVideoData(tempToken,appletsConfig,roomid);
                appletsBusinessTemplateLog.setTemplatetype("远程视频通知");
            }
            //日志保存
            appletsBusinessTemplateLog.setConfigId(appletsBusiness.getConfigId());
            appletsBusinessTemplateLog.setDeptId(appletsBusiness.getDeptId());
            appletsBusinessTemplateLog.setTemplateid(tempToken.getTemplate_id());
            appletsBusinessTemplateLog.setSendtype(appletsBusiness.getAreatype());
            appletsBusinessTemplateLog.setOpenid(tempToken.getOpenid());
            appletsBusinessTemplateLog.setBusinessid(appletsBusiness.getBusinessid());
            appletsBusinessTemplateLog.setTouser(appletsBusiness.getAllparty());
            SendWxMessage.getAccessToken(tempToken,false);//获取accesstoken
            appletsBusinessTemplateLog.setParamdata(JSON.toJSONString(tempToken));
            JSONObject msgJson=SendWxMessage.Push(tempToken,false);//发送消息
            if (msgJson.containsKey("errcode")){
                appletsBusinessTemplateLog.setErrcode(String.valueOf(msgJson.get("errcode")));
                //如果发送失败 就短信通知
                Map<String,String> resState = JSON.parseObject(JSON.toJSONString(ywInitData.getIdByConfigStateMap().get(configId)),Map.class);
                String message =  resState.get(BasicParamEnum.SYS_APPLETS_BASIC_MESSAGE.getKey()) == null?"false":resState.get(BasicParamEnum.SYS_APPLETS_BASIC_MESSAGE.getKey());
                if(!"0".equals(String.valueOf(msgJson.get("errcode")).trim()) && "true".equals(message)){
                    List<String> phonelist = new ArrayList<String>();
                    AppletsApplicantUser appletsApplicantUser=appletsApplicantUserService.selectAppletsApplicantUserByOpenId(tempToken.getOpenid());
                    if (!"".equals(StringUtils.isHcNull(appletsApplicantUser.getPhone(),""))){
                        phonelist.add("+86"+appletsApplicantUser.getPhone());
                        if("video".equals(type)){
                            sendAddOrder(phonelist, configId, "8",roomid,"","");
                        }else{
                            if("2".equals(appletsBusiness.getState())){
                                sendAddOrder(phonelist, configId, "3", appletsBusiness.getAllparty(),appletsBusiness.getBusinessid(),"");
                            }else if("98".equals(appletsBusiness.getState())){
                                sendAddOrder(phonelist, configId, "4", appletsBusiness.getAllparty(),appletsBusiness.getBusinessid(),"");
                            }else if("0".equals(appletsBusiness.getState())){
                                sendAddOrder(phonelist, configId, "5", appletsBusiness.getAllparty(),appletsBusiness.getBusinessid(),"");
                            }
                        }
                    }
                }
            }
            if (msgJson.containsKey("errmsg")){
                appletsBusinessTemplateLog.setErrmsg(String.valueOf(msgJson.get("errmsg")));
            }
            appletsBusinessTemplateLogService.insertAppletsBusinessTemplateLog(appletsBusinessTemplateLog);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    //小程序申办消息通知
    public void exeBidData(TempToken tempToken,AppletsBusiness appletsBusiness){
        String msg= modMsgLengthTMsg(20,appletsBusiness.getRemarks(),appletsBusiness.getState().trim());
        String matterName=appletsBusiness.getAllmatter();
        String [] matters = matterName.split(",");
        if(matters.length > 1)  {
            matterName = matters[0] + "、等";
        }
        Map<String, TemplateData> mData = new HashMap<>();
        mData.put("character_string9", new TemplateData(appletsBusiness.getBusinessid()));
        mData.put("thing11", new TemplateData(matterName));
        mData.put("phrase12", new TemplateData(ywInitData.getBusinessStateMap().get(appletsBusiness.getState().trim())));
        mData.put("thing7", new TemplateData(msg));
        tempToken.setData(mData);
    }
    //小程序补充材料消息通知
    public void exeMaterialsData(TempToken tempToken,AppletsBusiness appletsBusiness){
        String msg= modMsgLengthTMsg(20,appletsBusiness.getRemarks(),appletsBusiness.getState().trim());
        Map<String, TemplateData> mData = new HashMap<>();
        mData.put("character_string1", new TemplateData(appletsBusiness.getBusinessid()));
        mData.put("thing2", new TemplateData(msg));
        tempToken.setData(mData);
    }

    //远程视频消息通知
    public void exeVideoData(TempToken tempToken,AppletsConfig appletsConfig,String roomid){
        String msg= "请及时查看点击进入房间。";
        Map<String, TemplateData> mData = new HashMap<>();
        mData.put("number19", new TemplateData(roomid));
        mData.put("time17", new TemplateData(DateUtils.getTime()));
        mData.put("name4", new TemplateData(appletsConfig.getAbbreviation()));
        mData.put("thing9", new TemplateData(msg));
        tempToken.setData(mData);
    }
    //备注长度截取
    public static String modMsgLengthTMsg(int length,String str,String state){
      String msg=str;
      if ("2".equals(state)){//同意
          msg=StringUtils.isHcNull(msg,"您申办的业务审核已通过。");
          if (msg.length()>length){
              msg="您申办的业务审核已通过。";
          }
      } else if("98".equals(state)){
          msg=StringUtils.isHcNull(msg,"您申办的业务经审核，已拒绝办理。");
          if (msg.length()>length){
              msg="您申办的业务经审核，已拒绝办理。";
          }
      }else if("0".equals(state)){
          msg=StringUtils.isHcNull(msg,"您的申办缺少材料，请补充。");
          if (msg.length()>length){
              msg="您的申办缺少材料，请补充。";
          }
      }
      return msg;
    }
    //短信发送
    @Async
    public void sendAddOrder(List<String> phonelist, Long configId, String lx, String one, String two, String three) {
        try {
            BasicView basicView= JSON.parseObject(JSON.toJSONString(ywInitData.getIdByBasicViewMap().get(configId)),BasicView.class);
            MessageView messageView = basicView.getMessage();
            if (!StringUtils.isNull(messageView)){
                String secretId = StringUtils.isHcNull(messageView.getSecretId(),"");
                String secretKey = StringUtils.isHcNull(messageView.getSecretKey(),"");
                String SmsSdkAppid = StringUtils.isHcNull(messageView.getSdkAppid(),"");
                String sign = StringUtils.isHcNull(messageView.getSign(),"");
                TxSmsUtil.smsData(secretId,secretKey,SmsSdkAppid,sign,phonelist,lx,one,two,three);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }


    //生成小程序码
    public String getCodePath(AppletsPublicJishiban appletsPublicJishiban,String applicationId){
        String imgPath="";
        if ("1".equals(appletsPublicJishiban.getGenerateMode())){
            imgPath = appletsPublicJishiban.getAppletImg();
        }else{
            FileInfoView fileInfoView= FileUploadUtils.getUploadPath(SysFileTypeEnum.FILE_TYPE_IMG_PNG.getKey());
            TempToken tempToken = new TempToken(appletsPublicJishiban.getAppid(),appletsPublicJishiban.getAppsecret());
            SendWxMessage.getAccessToken(tempToken,false);//获取accesstoken
            boolean flag = SendWxMessage.getCode(tempToken,false,applicationId, fileInfoView.getPathFileName());
            if (flag){
                imgPath = fileInfoView.getFilePath();
            }else{
                imgPath = appletsPublicJishiban.getAppletImg();
            }
        }
        return imgPath;
    }
}
